﻿using BBCore.Application.ViewModels.Admins;
using BBCore.Core.Models.Admins;
using BBCore.Infrastructure.Helps;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using System.Diagnostics.CodeAnalysis;

namespace BBCore.Server.Components.Pages.Admins
{
    public partial class ChangePassword
    {
        private ValidateForm? _validateForm;
        private ChangePasswordVo _changePasswordVo = new ChangePasswordVo();
        [Parameter]
        [NotNull]
        public UserEntity? UserEntity { get; set; }

        [CascadingParameter]
        private Func<Task>? OnCloseAsync { get; set; }
        [Inject]
        [NotNull]
        private ToastService? ToastService { get; set; }

        private async Task OnValidSubmit(EditContext arg)
        {
            if (UserEntity.Password != MD5Encryption.Encrypt(_changePasswordVo.OldPassword!))
            {
                _validateForm?.SetError(nameof(ChangePasswordVo.OldPassword), "原密码不正确");
                return;
            }

            UserEntity.Password = MD5Encryption.Encrypt(_changePasswordVo.NewPassword!);
            await UserEntity.SaveAsync();


            if (OnCloseAsync != null)
            {
                await OnCloseAsync();
            }
            await ToastService.Show(new ToastOption()
            {
                Category = ToastCategory.Success,
                Title = "更改成功",
                Content = "密码更改成功,请重新登录"
            });
        }

    }
}
